from hjl_spider.stockpile.base import KeepBase
import json


class NotSeasonableJson(KeepBase):
    '''
    非即时保存json数据
    '''
    pass


class SeasonableJson(KeepBase):
    '''
    即时保存json数据
    '''
    name = "Seasonable-Json"

    @classmethod
    def save(cls, data, file_name="spider.json", encoding="utf-8",  **kwargs):
        '''
        保存方法
        :param file_name: 保存路径   file_name.json
        :param data: class："DataFile"
        :return:
        '''

        if cls.parm is None:  # 保存配置信息
            cls.parm = {
                "file_name": file_name,
                "encoding": encoding,
            }

        cls.data_queue.put(data)  # datafile->dict

    @classmethod
    def run(cls):
        '''
        实现数据保存
        :return:None
        '''
        das = []
        while not cls.data_queue.empty():
            data = cls.data_queue.get()

            # 保存文件

            das.append(data)

        with open(cls.parm["file_name"], 'w', encoding=cls.parm["encoding"]) as fp:
            fp.write(json.dumps(das, ensure_ascii=False))

    def __str__(self):
        return self.name



